package cn.easy.kitchen.web;

import cn.easy.base.bean.PageBean;
import cn.easy.base.utils.DateTimeUtil;
import cn.easy.base.web.BaseController;
import cn.easy.kitchen.bean.BomNutritionBean;
import cn.easy.kitchen.bean.GeoCoordBean;
import cn.easy.kitchen.bean.ShippingBean;
import cn.easy.kitchen.bean.StatNutritionBean;
import cn.easy.kitchen.domain.*;
import cn.easy.kitchen.service.*;
import cn.easy.kitchen.utils.ProjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/datav")
public class DataVController extends BaseController {
    @Autowired
    private StatSummaryService statSummaryService;
    @Autowired
    private StatNutritionService statNutritionService;
    @Autowired
    private StatMaterialPriceService statMaterialPriceService;
    @Autowired
    private StatMaterialStructureService statMaterialStructureService;
    @Autowired
    private BomService bomService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private MaterialBaseService materialBaseService;
    @Autowired
    private MaterialOrderService materialOrderService;

    private final BigDecimal DEFAULT_X_AXIS = new BigDecimal(120.268152);
    private final BigDecimal DEFAULT_Y_AXIS = new BigDecimal(29.76381);

    @RequestMapping("")
    String index(String type, HttpServletRequest request, Model model) {
        if (StringUtils.isBlank(type)) {
            type = "default";
        }
        model.addAttribute("type", type);
        model.addAttribute("recommendMenus", bomService.searchByParams(genSearchParams(request, type)));
        model.addAttribute("countSchool", customerService.countSchool());
        model.addAttribute("countBom", bomService.countBom());
        model.addAttribute("countMaterial", materialBaseService.countMaterialBase());
        model.addAttribute("statMaterialStructure_total", statMaterialStructureService.searchByParams(genSearchParams(request, type), new PageBean()).getTotalPages());
        model.addAttribute("statNutritionAnalysis_total", statNutritionService.pageByParams(genSearchParams(request, type), new PageBean()).getTotalPages());
        if ("old".equals(requestParams(request).get("version"))) {
            return "datav/index_old";
        }
        return "datav/index";
    }


    /**
     * 地图配送数据
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/shippingMap")
    @ResponseBody
    Map<String, Object> shippingMap(String type, HttpServletRequest request, Model model) {
        PageBean pageBean = new PageBean();
        //20个一组
        pageBean.setTotalPages(20);
        int currentPage = (int) (Math.random() * 5);
        pageBean.setCurrentPage(currentPage == 0 ? 1 : currentPage);
        Map<String, Object> searchParams = searchParams(request);
        //只取学校
        searchParams.put("IN_customerTypeId", "00000000000000000000000000000001,00000000000000000000000000000004");
        searchParams.put("EQ_area", "诸暨市");
        Page<Customer> page = customerService.search(searchParams, pageBean);
        Map<String, Object> resultMap = new HashMap<>();
        List<GeoCoordBean> geoCoordList = new ArrayList<>();
        List<ShippingBean> shippingLinesList = new ArrayList<>();
        if (page.getContent() != null) {
            for (Customer customer : page.getContent()) {
                geoCoordList.add(new GeoCoordBean(customer.getShortName(), customer.getXaxis(), customer.getYaxis(), BigDecimal.valueOf(Math.random() * 50)));
                shippingLinesList.add(new ShippingBean("配送站", customer.getShortName(), DEFAULT_X_AXIS, DEFAULT_Y_AXIS,
                        customer.getXaxis(), customer.getYaxis()));
            }
        }
        //官方样例里需要多加一个起始站的数据
        geoCoordList.add(new GeoCoordBean("配送站", DEFAULT_X_AXIS, DEFAULT_Y_AXIS, BigDecimal.valueOf(100)));
        resultMap.put("geoCoordList", geoCoordList);
        resultMap.put("shippingLinesList", shippingLinesList);
        return resultMap;
    }

    /**
     * 学校统计报表
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/statSummaryList")
    @ResponseBody
    List<StatSummary> getStatSummaryList(String type, HttpServletRequest request, Model model) {
        return statSummaryService.search(genSearchParams(request, type));
    }

    /**
     * 物料价格报表
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/statMaterialPriceList")
    @ResponseBody
    List<StatMaterialPrice> getStatMaterialPriceList(String type, HttpServletRequest request, Model model) {
        Map<String, Object> searchParams = searchParams(request);
        int year = 2017;
        //本年、默认之外，全部都是取本月的数据
        if ("thisYear".equals(type) || "default".equals(type)) {
            searchParams.put("GTE_dataOn", DateTimeUtil.getStartMonth(year, 2));
            searchParams.put("LTE_dataOn", DateTimeUtil.getEndMonth(year, 6));
        } else {
            searchParams.put("GTE_dataOn", DateTimeUtil.getStartMonth(year, 6));
            searchParams.put("LTE_dataOn", DateTimeUtil.getEndMonth(year, 6));
        }
        return statMaterialPriceService.searchByParams(searchParams, type);
    }

    /**
     * 营养摄入对比
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/statNutritionCompareList")
    @ResponseBody
    StatNutritionBean getStatNutritionCompareList(String type, HttpServletRequest request, Model model) {
        return statNutritionService.searchByParams(genSearchParams(request, type));
    }

    /**
     * 营养摄入分析
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/statNutritionAnalysisList")
    @ResponseBody
    List<StatNutrition> statNutritionAnalysisList(String type, int currentPage, HttpServletRequest request, Model model) {
        PageBean pageBean = new PageBean();
        pageBean.setTotalPages(6);
        pageBean.setCurrentPage(currentPage);
        List<StatNutrition> list = statNutritionService.pageByParams(genSearchParams(request, type), pageBean).getContent();
        Collections.reverse(list);
        return list;
    }

    /**
     * 食材结构报表
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/statMaterialStructureList")
    @ResponseBody
    List<StatMaterialStructure> getMaterialStructureList(String type, int currentPage, HttpServletRequest request, Model model) {
        PageBean pageBean = new PageBean();
        pageBean.setTotalPages(5);
        pageBean.setCurrentPage(currentPage);
        List<StatMaterialStructure> list = statMaterialStructureService.searchByParams(genSearchParams(request, type), pageBean).getContent();
        Collections.reverse(list);
        return list;
    }

    /**
     * 菜谱推荐,今日采购列表
     *
     * @param type
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/statRecommendedMenuList")
    String recommendedMenuList(String type, HttpServletRequest request, Model model) {
        model.addAttribute("recommendMenus", materialOrderService.searchByParams(genSearchParams(request, type)));
        return "datav/recommendMenu_template";
    }


    /**
     * 根据查询类型，组装查询的开始时间和结束时间
     * type：default，today，thisMonth，thisYear
     *
     * @param request
     * @param type
     * @return
     */
    private Map<String, Object> genSearchParams(HttpServletRequest request, String type) {
        Map<String, Object> searchParams = searchParams(request);
        if (ProjectUtil.isValidParam(searchParams, "EQ_customerName")) {
            Customer customer = customerService.findByShortName(searchParams.get("EQ_customerName").toString());
            searchParams.put("EQ_customerId", customer.getId());
        }
        int year = 2017;
        switch (type) {
            case "default":
                searchParams.put("GTE_dataOn", DateTimeUtil.getStartMonth(year, 0));
                searchParams.put("LTE_dataOn", DateTimeUtil.getEndMonth(year, 6));
                break;
            case "today":
                searchParams.put("GTE_dataOn", DateTimeUtil.addYear(DateTimeUtil.getStartDate(new Date()), -1));
                searchParams.put("LTE_dataOn", DateTimeUtil.addYear(DateTimeUtil.getEndDate(new Date()), -1));
                break;
            case "thisMonth":
                searchParams.put("GTE_dataOn", DateTimeUtil.getStartMonth(year, 6));
                searchParams.put("LTE_dataOn", DateTimeUtil.getEndMonth(year, 6));
                break;
            case "thisYear":
                searchParams.put("GTE_dataOn", DateTimeUtil.getStartMonth(year, 0));
                searchParams.put("LTE_dataOn", DateTimeUtil.getEndMonth(year, 6));
                break;

        }
        return searchParams;
    }
}
